package com.example.concurrent;

import java.util.ArrayList;

import cn.hutool.core.lang.Console;

public class TestThreadSafe {
	private static final int THREAD_NUMBER = 5;
	private static final int LOOP_NUMBER = 1000;

	public static void main(String[] args) {
		ThreadSafeSubClass test = new ThreadSafeSubClass();
		for (int i = 0; i < THREAD_NUMBER; i++) {
			new Thread(
					()->{
						test.method1(LOOP_NUMBER);
					},
					"Thead"+(i+1)
					).start();
		}
		Console.log("RUN OVER");
	}
}

class ThreadUnsafe{
	ArrayList<String> list = new ArrayList<>();
	public void method1(int loopNumber) {
		for (int i = 0; i < loopNumber; i++) {
			method2();
			method3();
		}
	}
	private void method2() {
		list.add("1");
	}
	private void method3() {
		list.remove(0);
	}
}


class ThreadSafe{
	public final void method1(int loopNumber) {
		ArrayList<String> list = new ArrayList<>();
		for (int i = 0; i < loopNumber; i++) {
			method2(list);
			method3(list);
		}
	}
	private void method2(ArrayList<String> list) {
		list.add("1");
	}
	private void method3(ArrayList<String> list) {
		list.remove(0);
	}
}

class ThreadSafeSubClass extends ThreadSafe{

	public void method3(ArrayList<String> list) {
		new Thread(
				()->{
					list.remove(0);
				}
				).start();
	}
}